<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form onsubmit="return false">
    <label for="username">用户名:</label>
    <input type="text" id="username" name="username"><br/>
    <label for="username">密码:</label>
    <input type="password" id="password" name="password"><br/>
    <input type="button" value="登录" onclick="handleSubmit()"><br/>
</form>
<script>
    function handleSubmit() {
        let user = {
            username: document.querySelector("#username").value,
            password: document.querySelector("#password").value
        }
        fetch("/login", {
            method: 'POST',
            body: JSON.stringify(user),
            headers: {
                'content-type': "application/json"
            }
        }).then(res => {
            return res.json();
        }).then(res => {
            console.log(res)
            // 将获取的 token 存储到 localStorage
            localStorage.setItem("token", res.token)
            location.href = "/index"
        })
    }

    // 校验是否含有token
    {
        let token = localStorage.getItem("token")
        if (token) {
            fetch("/gateway", {
                headers: {
                    "token": token
                }
            }).then(res => {
                return res.json()
            }).then(res => {
                if (res.code === 0) {
                    location.href = "/index"
                } else {
                    // token 过期移除过期的 token
                    localStorage.removeItem("token")
                    alert(res.msg)
                }
            })
        }
    }
</script>
</body>
</html>